package com.zllkj.mm.module.moment

import android.content.Intent
import android.content.res.Configuration
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.orhanobut.hawk.Hawk
import com.previewlibrary.GPreviewBuilder
import com.tencent.bugly.crashreport.biz.UserInfoBean
import com.zllkj.mm.R
import com.zllkj.mm.adapter.CommentListAdapter
import com.zllkj.mm.api.network.RetrofitHelper
import com.zllkj.mm.api.network.RxHelper
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber
import com.zllkj.mm.base.BaseTitleFragment
import com.zllkj.mm.common.L
import com.zllkj.mm.model.entity.*
import com.zllkj.mm.module.goods.VideoPlayerDetailedActivity
import com.zllkj.mm.module.goods.vm.ItemCommentVM
import com.zllkj.mm.module.shopping.vm.ItemFriendListVM
import com.zllkj.mm.util.common.FormatUtil
import com.zllkj.mm.util.common.PictureLoadUtil
import kotlinx.android.synthetic.main.fragment_friend_detail.view.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

class FriendDetailFragment(val vm:ItemFriendListVM) : BaseTitleFragment(),TextView.OnEditorActionListener {


    var currentPage = 1
    var datas = ArrayList<ItemCommentVM>()
    var DY_TYPE_FREE = 1
    var DY_TYPE_NORMAL = 2
    var COMMENT_TYPE_PARENT = 0
    var COMMEET_TYPE_SUB = 1
    var COMMENT_TYPE_THIRD = 2
    var currentCommentType = COMMENT_TYPE_PARENT
    var subPosition = -1;
    var thirdPosition = -1

    lateinit var commentAdapter : CommentListAdapter

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_friend_detail
    }

    override fun loadData() {
        super.loadData()

        setCommonTitle("动态详情")

       loadCarryDataFromList()

       loadComment()
    }

    override fun onKeyBoardShow() {
        super.onKeyBoardShow()
        if(vm?.userDyBean?.dynamicType == DY_TYPE_FREE) {
            mRootView.btn_invite_time.visibility = View.GONE
        }
    }

    override fun onKeyBoardHide() {
        super.onKeyBoardHide()
        mRootView.ed_add_comment.visibility = View.GONE
        if(vm?.userDyBean?.dynamicType == DY_TYPE_FREE) {
            mRootView.btn_invite_time.visibility = View.VISIBLE
        }
    }


    fun addComment(dynamicCommentId:String){
        addSubscribe(RetrofitHelper.getInstance().dynamicApi.addComment((HashMap<String, Any>().apply {
            this["dynamicId"] = vm.userDyBean?.dynamicId.toString()
            this["dynamicCommentId"] = dynamicCommentId
            this["content"] = mRootView.ed_add_comment.text.toString()
        })).compose<CommentReplyVo>(RxHelper.defaultHandleResult<CommentReplyVo>()).subscribe(object : ProgressSubscriber<CommentReplyVo>(context) {
            override fun onSucc(t: CommentReplyVo?) {
                if (currentCommentType == COMMENT_TYPE_PARENT) {
                    datas.add(ItemCommentVM().apply {
                        this.commentId = t?.dynamicCommentId.toString()
                        this.content = mRootView.ed_add_comment.text.toString()
                        this.time = SimpleDateFormat("yyyy-MM-dd hh:mm:SS").format(Date())
                        this.name = Hawk.get<UserSelfVo>(L.userInfo).nikeName
                        this.url = Hawk.get<UserSelfVo>(L.userInfo).userLogo
                        this.subList = ArrayList()
                    })
                } else if (currentCommentType == COMMEET_TYPE_SUB) {
                    var son = SonDynamicCommentPage(
                            beReplyNikeName =datas[subPosition].name,
                            content = mRootView.ed_add_comment.text.toString(),
                            createTime = SimpleDateFormat("yyyy-MM-dd hh:mm:SS").format(Date()),
                            dynamicCommentId = t?.dynamicCommentId!!,
                            dynamicId = vm.userDyBean?.dynamicId!!,
                            userLogo = Hawk.get<UserSelfVo>(L.userInfo).userLogo,
                            nikeName = Hawk.get<UserSelfVo>(L.userInfo).nikeName,replyUserId = 1,userId = 1)

                    datas[subPosition].subList.add(son)

                } else if (currentCommentType == COMMENT_TYPE_THIRD) {
                    var son = SonDynamicCommentPage(
                            beReplyNikeName =datas[subPosition].subList[thirdPosition].nikeName,
                            content = mRootView.ed_add_comment.text.toString(),
                            createTime = SimpleDateFormat("yyyy-MM-dd hh:mm:SS").format(Date()),
                            dynamicCommentId = t?.dynamicCommentId!!,
                            dynamicId = vm.userDyBean?.dynamicId!!,
                            userLogo = Hawk.get<UserSelfVo>(L.userInfo).userLogo,
                            nikeName = Hawk.get<UserSelfVo>(L.userInfo).nikeName,replyUserId = 1,userId = 1)

                    datas[subPosition].subList.add(son)
                }
                mRootView.ed_add_comment.setText("")
                commentAdapter.notifyDataSetChanged()
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }

    /**
     *
     */
    fun loadComment(){
        datas.clear()
        mRootView.rv_comment_list.layoutManager = LinearLayoutManager(requireContext())
        mRootView.rv_comment_list.adapter = commentAdapter
        addSubscribe(RetrofitHelper.getInstance().api.dynamicCommentList((HashMap<String, Any>().apply {
            this["dynamicId"] = vm.userDyBean?.dynamicId.toString()
            this["currentPage"] = currentPage
            this["pageSize"] = 20
        })).compose<DynamicCommentVo>(RxHelper.defaultHandleResult<DynamicCommentVo>()).subscribe(object : ProgressSubscriber<DynamicCommentVo>(context) {
            override fun onSucc(t: DynamicCommentVo?) {
                t?.records?.map {
                    var vm = ItemCommentVM()
                    vm.content = it.content
                    vm.time = it.createTime
                    vm.name = it.nikeName
                    vm.url = it.userLogo
                    vm.commentId = it.dynamicCommentId.toString()
                    vm.subList.addAll(it.sonDynamicCommentPage)
                    datas.add(vm)
                    commentAdapter.notifyDataSetChanged()
                }
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }

    fun loadCarryDataFromList(){
        var gridView = mRootView.rv_nine_data
        if(vm.imageList.size == 1 && vm.imageList[0].url == "") {
            gridView.visibility = View.GONE
        }
        gridView.layoutManager = GridLayoutManager(requireContext(),3,GridLayoutManager.VERTICAL,false)
        var adapter = object : BaseQuickAdapter<GridImageViewBean,BaseViewHolder>(R.layout.item_9_friend_image,vm.imageList){
            override fun convert(p0: BaseViewHolder?, p1: GridImageViewBean?) {
                p1?.let {
                    if (it.url != null) {
                        p0?.getView<AppCompatImageView>(R.id.iv_nine_image)?.let { it1 ->
                            PictureLoadUtil.loadPic(it1, p1.url!!)
                        }
                    }
                    if (it.videoUrl != null) {
                        p0?.getView<AppCompatImageView>(R.id.iv_video_play_icon)?.visibility = View.VISIBLE
                        p0?.getView<AppCompatImageView>(R.id.iv_nine_image)?.let { it1 ->
                            PictureLoadUtil.loadImageFromOnLineUrl(it1, p1.url!!)
                        }
                    }

                }
            }
        }
        gridView.adapter = adapter
        adapter.setOnItemClickListener { baseQuickAdapter, view, i ->
            if(!TextUtils.isEmpty( vm.imageList[i].videoUrl)){

                val intent = Intent(requireActivity(), VideoPlayerDetailedActivity::class.java)
                intent.putExtra("url", vm.imageList[i].videoUrl)
                requireActivity().startActivity(intent)
            } else {
                GPreviewBuilder.from(requireActivity())
                        .setData(vm.imageList)
                        .setIsScale(true)
                        .setCurrentIndex(i)
                        .setType(GPreviewBuilder.IndicatorType.Dot)
                        .start() //启动
            }

        }

        mRootView.ed_add_comment.setOnEditorActionListener(this)


        commentAdapter = CommentListAdapter(R.layout.item_comment_list,datas)
        commentAdapter.setOnItemChildClickListener { baseQuickAdapter, view, i ->
            subPosition = i
            if (view.id == R.id.tv_replay_text) {
                mRootView.ed_add_comment.visibility = View.VISIBLE
                showSoftInput(mRootView.ed_add_comment)
                currentCommentType = COMMEET_TYPE_SUB
            }

        }

        commentAdapter.sonCommentClickedListener = object : CommentListAdapter.SonCommentClickedListener{
            override fun onClicked(parentPosition: Int, sonPosotion: Int) {
                subPosition =  parentPosition
                thirdPosition = sonPosotion

                mRootView.ed_add_comment.visibility = View.VISIBLE
                showSoftInput(mRootView.ed_add_comment)
                currentCommentType = COMMENT_TYPE_THIRD
            }

        }

        mRootView.ed_replyEt.setOnClickListener {
            currentCommentType = COMMENT_TYPE_PARENT
            mRootView.ed_add_comment.visibility = View.VISIBLE
            showSoftInput(mRootView.ed_add_comment)

        }


        vm.userDyBean?.let {
            var ivHead = mRootView.ivhead
            mRootView.tvUserName.text = it.nikeName
            mRootView.tv_item_friend_content.text = it.content
            mRootView.tv_item_friend_comment_num.text = it.commentNum.toString()
            mRootView.tv_item_friend_like_num.text = it.likeNum.toString()
            var address = "|" + it.province + it.city + it.district
            mRootView.tv_age_and_sex.text = if(it.sex == 1)"男" else "女"  + "|" + it?.province + it.city + it.district
            mRootView.tv_age_and_sex.append(address)

            PictureLoadUtil.loadPic(ivHead,vm.userDyBean!!.userLogo)

            if(it.dynamicType == 1) {
                mRootView.ll_invite_time_area.visibility = View.VISIBLE
                mRootView.tv_friend_invite_money.text = FormatUtil.bigDecimalUtilFormat(it?.price,"100") + "/次"
                mRootView.tv_friend_invite_time.text = FormatUtil.dataFormat(it.createTime)
            }

            mRootView.tv_item_friend_like_num.text = it.likeNum.toString()

            if (it.dynamicType == 1) {
                mRootView.btn_invite_time.visibility = View.VISIBLE
            } else {
                mRootView.btn_invite_time.visibility = View.GONE
            }
        }

        mRootView.btn_invite_time.setOnClickListener {
            addFragment(FreeTimeInviteFragment(vm))

        }

    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (currentCommentType == COMMENT_TYPE_PARENT){ //一級
            addComment("")
        } else if (currentCommentType == COMMEET_TYPE_SUB) { //2級
            addComment(datas[subPosition].commentId)
        } else if (currentCommentType == COMMENT_TYPE_THIRD) { //三級
            addComment(datas[subPosition].subList[thirdPosition].dynamicCommentId.toString())
        }

        mRootView.ed_add_comment.visibility = View.GONE
        hideSoftInput()

        return true
    }
}